#!/usr/bin/env python
# -*- coding:utf-8 -*-
import shutil
import os,re,sys
import subprocess
import time
from typing import Optional
from madb.tools.printer import info,plus,warn
try:
    from madb.adb.settings import command
except Exception as e:
    print("adb命令的环境变量未设置!")
    time.sleep(1)
    sys.exit()

class Adb(object):
    def __init__(self,device=None):
        self.device = device
        self.command = []
        self.output = ""
    def execute(self,choice="1",is_async:bool=False,timeout:Optional[int]=None):
        try:
            if choice in command.keys():
                self.command = command[choice]
            else:
                self.command = command["1"]
            
            if is_async:
                subprocess.Popen(self.command)
                return None
            
            process = subprocess.Popen(
                self.command,
                stdout = subprocess.PIPE,
                stderr = subprocess.STDOUT
            )
            
            output = (
                process.communicate(timeout=timeout)[0].strip()
                .decode(errors='strict')
            )
            
            if process.returncode == 0 :
                self.output = output
                plus(" ".join(self.command))
                info(output)
            else:
                raise subprocess.CalledProcessError(
                process.returncode, command, output.encode()
                )
            time.sleep(1)
        except Exception as e:
            warn("命令: {0}".format(" ".join(self.command)))
            warn(e.output.decode(errors='strict'))
            warn("命令执行错误!")
    def customize_execute(self,command:list,is_async:bool=False,timeout:Optional[int]=None):
        try:
            print(command)    
            if is_async:
                subprocess.Popen(command)
                return None
            
            process = subprocess.Popen(
                command,
                stdout = subprocess.PIPE,
                stderr = subprocess.STDOUT
            )
            
            output = (
                process.communicate(timeout=timeout)[0].strip()
                .decode(errors='strict')
            )
            
            if process.returncode == 0 :
                self.output = output
                plus(" ".join(command))
                info(output)
            else:
                raise subprocess.CalledProcessError(
                process.returncode, command, output.encode()
                )
            time.sleep(1)
        except Exception as e:
            warn("命令: {0}".format(" ".join(self.command)))
            warn(e.output.decode(errors='strict'))
            warn("命令执行错误!")        


